#![cfg_attr(feature = "axstd", no_std)]
#![cfg_attr(feature = "axstd", no_main)]

extern crate axplat_aarch64_phytium_pi;

#[cfg(feature = "axstd")]
use axstd::println;

use axhal::fiomux::*;
use axhal::pwm::*;

#[cfg_attr(feature = "axstd", unsafe(no_mangle))]
fn main() {
    println!("飞腾派PWM风扇控制演示");

    // 初始化IOMUX
    println!("初始化IOMUX...");
    fiomux_init();

    // 设置PWM引脚复用
    println!("设置PWM引脚复用...");
    fiopad_set_pwm_mux(0, 1); // FPWM0_ID, PWM_TEST_CHANNEL=1
    println!("PWM引脚复用设置完成");

    // 初始化PWM控制器
    println!("正在初始化PWM控制器...");

    // 创建PWM系统实例
    let mut pwm_system = PwmSystem::new();

    // 配置通道1 (PWM_TEST_CHANNEL = FPWM_CHANNEL_1)
    let config = PwmConfig {
        frequency: 10000, // 10kHz频率
        duty_cycle: 0.2,  // 20%初始占空比
        counting_mode: 0, // Modulo模式
        deadtime_ns: None,
        use_fifo: false,
        output_behavior: 5, // FPWM_POLARITY_INVERTED (0b101)
        initial_value: 0,
    };

    println!("开始配置PWM通道...");
    // 获取PWM0控制器 (FPWM0_ID)
    let pwm_controller = pwm_system.controller(0).unwrap();

    // 配置并启用PWM通道
    match pwm_controller.configure_channel(1, config) {
        Ok(()) => {
            println!("PWM通道配置成功");
        }
        Err(e) => {
            println!("PWM通道配置失败: {}", e);
            return;
        }
    }

    println!("开始启用PWM通道...");
    // 启用PWM通道
    let pwm_controller = pwm_system.controller(0).unwrap();
    match pwm_controller.enable_channel(1) {
        Ok(()) => {
            println!("PWM通道启用成功，风扇已启动");
        }
        Err(e) => {
            println!("PWM通道启用失败: {}", e);
            return;
        }
    }

    println!("启用全局PWM...");
    // 启用全局PWM
    pwm_system.global_enable();
    println!("全局PWM使能完成");

    // 添加额外的确认信息
    println!("PWM控制器已配置并启用");
    println!("预期行为：风扇应该开始转动，并且每5秒改变一次转速");

    let mut duty = 20; // 从20%占空比开始

    loop {
        // 动态调整风扇转速
        let new_duty_cycle = duty as f32 / 100.0;
        println!("准备设置新的占空比: {}%", duty);

        // 重新配置通道以应用新的占空比
        let new_config = PwmConfig {
            frequency: 10000, // 10kHz频率
            duty_cycle: new_duty_cycle,
            counting_mode: 0, // Modulo模式
            deadtime_ns: None,
            use_fifo: false,
            output_behavior: 5, // FPWM_POLARITY_INVERTED
            initial_value: 0,
        };

        // 重新获取控制器引用以避免借用冲突
        let pwm_controller = pwm_system.controller(0).unwrap();
        match pwm_controller.configure_channel(1, new_config) {
            Ok(()) => {
                println!("风扇占空比已调整为{}%", duty);
            }
            Err(e) => {
                println!("调整风扇占空比失败: {}", e);
            }
        }

        // 重新启用通道
        let pwm_controller = pwm_system.controller(0).unwrap();
        if let Err(e) = pwm_controller.enable_channel(1) {
            println!("重新启用PWM通道失败: {}", e);
        }

        // 增加占空比，循环范围20%-100%
        duty = if duty >= 100 { 20 } else { duty + 20 };

        // 等待一段时间再调整
        #[cfg(feature = "axstd")]
        axstd::thread::sleep(axstd::time::Duration::from_secs(5));
        #[cfg(not(feature = "axstd"))]
        axhal::time::busy_wait_for(axhal::time::DurationNanos::from_secs(5));
    }
}
